/*!
 * \file cicsts_core.h
 *
 * \brief CICSTS模块主文件
 *
 * All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.
 *
 * \version 1.0
 * \author songbb
 * \date 2016/04/22
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>

#include "frcomm.h"
#include "frstr.h"
#include "frhash2.h"
#include "frmem.h"
#include "frlog.h"
#include "frsutl.h"
#include "frreport_comm.h"

#include "conntrack.h"
#include "frct_comm.h"
#include "frversion.h"

#include "cicsts_comm.h"
#include "cicsts_core.h"
#include "cicsts_header.h"
#include "cicsts_packet.h"
#include "cicsts_trans.h"

/*******************************************************************************
*  FUNC     :  CicsTS Session初始化
*  ARGS     :  *p_st_session                            (L7层session信息)
*  RTN      :  0                                        (FR_SUCC)
*              1                                        (FR_FAIL)
*  NOTE     :
*******************************************************************************/
FR_STATIC int __cicsts_private_session_init(L7_session *p_st_session)
{
    CICSTS_PRINT_INFO("session init\n");
    L7session_cicsts_private *p_st_cicsts_private = NULL;      // CICSTS的私有信息
    L7_cicsts_packet *p_st_cicsts_packet = NULL;               // CICSTS格式的packet包
    Frhash_header *p_hash_stmt = NULL;                     // CICSTS的statement信息结构

    // 1. 初始化CicsTS格式的packet包
    if ((p_st_cicsts_packet = (L7_cicsts_packet *) frmalloc(sizeof(L7_cicsts_packet))) == NULL)
    {
        CICSTS_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_cicsts_packet, 0x00, sizeof(L7_cicsts_packet));
    if (cicsts_init_packet(p_st_cicsts_packet) != FR_SUCC)
        goto error;

    // 2. 初始化statement hash
    if ((p_hash_stmt = (Frhash_header *) frmalloc(sizeof(Frhash_header))) == NULL)
    {
        CICSTS_MALLOCK_ERR;
        goto error;
    }
    memset(p_hash_stmt, 0x00, sizeof(Frhash_header));
    if (frhash2_create(p_hash_stmt, APM_CICSTS_HASH_SIZE) != FR_SUCC)
    {
        CICSTS_FRLOG_ERROR("frhash2_create fail");
        goto error;
    }

    // 3. 创建和初始化CicsTS的私有信息
    if ((p_st_cicsts_private = (L7session_cicsts_private *) frmalloc(sizeof(L7session_cicsts_private))) == NULL)
    {
        CICSTS_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_cicsts_private, 0x00, sizeof(L7session_cicsts_private));
    p_st_cicsts_private->p_st_cicsts_packet = p_st_cicsts_packet;
    p_st_cicsts_private->p_st_session = p_st_session;
    p_st_cicsts_private->p_hash_stmt = p_hash_stmt;

    // 4. 设置L7_session的p_session_private信息
    frct_set_session_private(p_st_session, (void *)p_st_cicsts_private);

    return FR_SUCC;
error:
    if (p_st_cicsts_packet != NULL)
    {
        bytebuff_free(&(p_st_cicsts_packet->p_st_packet));
        cicsts_free((void **) &p_st_cicsts_packet);
    }
    frhash2_free2(p_hash_stmt, cicsts_stmt_node_free);
    cicsts_free((void **) &p_st_cicsts_private);
    return FR_FAIL;
}

int cicsts_detect(Conntrack *p_st_conn
                , Apm_packet *p_st_packet)
{
    CICSTS_PRINT_INFO("cicsts_detect\n");

#if APM_CICSTS_DBG
    char arr_ip_src[56], arr_ip_dst[56];
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->dst_ip));
    CICSTS_PRINT_TIMEVAL("PacketIn", p_st_packet->st_timestamp);
    CICSTS_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] Length:[%u]\n", arr_ip_src, p_st_packet->src_port, arr_ip_dst, p_st_packet->dst_port, p_st_packet->ui_payload_len);
#endif

    return APM_L7_IS_UNKNOWN;
}

int cicsts_analyze(Conntrack *p_st_conn
                , Apm_packet *p_st_packet
                , Frhash_header *p_st_hash_report)
{
    CICSTS_PRINT_INFO("cicsts_analyze\n");
    L7_session *p_st_session = NULL;
    L7session_cicsts_private *p_st_session_private = NULL;
    L7_cicsts_packet *p_st_cicsts_packet = NULL;
    int i_unfragmented_ret = 0;
    int i_analyze_ret = 0;                  // 本函数的返回值
    char arr_ip_src[56], arr_ip_dst[56];

    if(p_st_conn == NULL || p_st_packet == NULL
      || p_st_hash_report == NULL)
        return APM_L7_ANALYZE_FAIL;

    p_st_session = frct_get_session(p_st_conn);
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->dst_ip));

    CICSTS_PRINT_TIMEVAL("PacketIn", p_st_packet->st_timestamp);
    CICSTS_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] SessionID:[%s]\n", arr_ip_src, p_st_packet->src_port, arr_ip_dst, p_st_packet->dst_port, p_st_session->arr_session_id);

    /*
    * 如果入力p_st_packet是FIN包, 说明本次connection结束,
    * 释放本次session信息. 如果入力p_st_packet是SYN包,说明新的
    * connection开始了, 释放上次可能残留的session信息
    */
    if (p_st_packet->em_analyz_cmd == FRANALYZ_CMD_FIN || p_st_packet->em_analyz_cmd == FRANALYZ_CMD_SYN)
    {
        if (p_st_packet->em_analyz_cmd == FRANALYZ_CMD_SYN)
            CICSTS_PRINT_INFO("SYN PACKET\n");
        else if (p_st_packet->em_analyz_cmd == FRANALYZ_CMD_FIN)
            CICSTS_PRINT_INFO("FIN PACKET\n");
        if (p_st_session->p_session_private != NULL)
        {
            cicsts_session_destory(p_st_session->p_session_private);
            p_st_session->p_session_private = NULL;
        }
        CICSTS_PRINT("### i_analyze_ret:[%d]\n\n", APM_L7_ANALYZE_SUCC);
        return APM_L7_ANALYZE_SUCC;
    }

    // 本次链路的第一个有效packet包,创建链路
    if (p_st_session->p_session_private == NULL)
    {
        // 初始化CicsTS的session数据
        if (__cicsts_private_session_init(p_st_session) != FR_SUCC)
            goto cicsts_analyze_fail;

        // 设置session uuid
        fruuid(p_st_session->arr_session_id);
    }

    // 打印方向
    switch (p_st_packet->i_direction)
    {
        case FR_DIRECT_CLIENT2SRV:
            CICSTS_PRINT("client["KLIMEGREEN"%s:%d"RESET"] to server["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] ->>>>>>>>>>>>>>>>>>>>>>>\n",
                      arr_ip_src,
                      p_st_packet->src_port,
                      arr_ip_dst,
                      p_st_packet->dst_port,
                      p_st_packet->ui_payload_len);
            break;
        case FR_DIRECT_SRV2CLIENT:
            CICSTS_PRINT("server["KLIMEGREEN"%s:%d"RESET"] to client["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] <<<<<<<<<<<<<<<<<<<<<<<-\n",
                      arr_ip_src,
                      p_st_packet->src_port,
                      arr_ip_dst,
                      p_st_packet->dst_port,
                      p_st_packet->ui_payload_len);
            break;
        default:
            CICSTS_PRINT("unknown direction, src["KLIMEGREEN"%s:%d"RESET"], dest["KLIMEGREEN"%s:%d"RESET"]\n",
                      arr_ip_src,
                      p_st_packet->src_port,
                      arr_ip_dst,
                      p_st_packet->dst_port);
            goto cicsts_analyze_fail;
    }

    p_st_session_private = (L7session_cicsts_private *) frct_get_session_private(p_st_session);
    p_st_cicsts_packet = p_st_session_private->p_st_cicsts_packet;

    i_unfragmented_ret = cicsts_packet_unfragment(p_st_packet, p_st_cicsts_packet);
    if (i_unfragmented_ret == APM_CICSTS_CHECK_FRAGMENT_NEED_NEXT_PACKET)
        goto cicsts_analyze_todo;
    else if (i_unfragmented_ret == APM_CICSTS_CHECK_FRAGMENT_ERROR)
        goto cicsts_analyze_fail;

    if (p_st_packet->i_direction == FR_DIRECT_CLIENT2SRV)
    {
        if (cicsts_req(p_st_conn, p_st_cicsts_packet, p_st_hash_report) == FR_SUCC)
        {
            i_analyze_ret = APM_L7_ANALYZE_SET_REQ(APM_L7_ANALYZE_SUCC);
            goto cicsts_analyze_success;
        }
    }
    else
    {
        if (cicsts_resp(p_st_conn, p_st_cicsts_packet, p_st_hash_report) == FR_SUCC)
        {
            i_analyze_ret = APM_L7_ANALYZE_SET_RESP(APM_L7_ANALYZE_SUCC);
            goto cicsts_analyze_success;
        }
    }

cicsts_analyze_todo:
    CICSTS_PRINT("### i_analyze_ret todo:[%d]\n\n", APM_L7_ANALYZE_TODO);
    return APM_L7_ANALYZE_TODO;

cicsts_analyze_success:
    CICSTS_PRINT("### i_analyze_ret success:[%d]\n\n", i_analyze_ret);
    return i_analyze_ret;

cicsts_analyze_fail:
    if (cicsts_packet_is_in_fragment(p_st_cicsts_packet))
    {
        if (bytebuff_setPosition(p_st_cicsts_packet->p_st_packet, 0) != FR_SUCC)
        {
            p_st_cicsts_packet->fragment_state = APM_CICSTS_FRAGMENT_INIT;
            return APM_L7_ANALYZE_FAIL;
        }
        goto cicsts_analyze_todo;
    }
    else
    {
        CICSTS_PRINT_PACKET("error packet", p_st_cicsts_packet);
        cicsts_init_packet(p_st_cicsts_packet);
    }

    CICSTS_PRINT_EMERG("### i_analyze_ret fail:[%d]\n\n", APM_L7_ANALYZE_FAIL);
    return APM_L7_ANALYZE_FAIL;
}

/*******************************************************************************
*  FUNC     :  释放 L7_cicsts_packet
*  ARGS     :  **pp_st_cicsts_packet              (L7_cicsts_packet)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __cicsts_destroy_packet(L7_cicsts_packet **pp_st_cicsts_packet)
{
    if (pp_st_cicsts_packet == NULL || *pp_st_cicsts_packet == NULL)
        return;

    L7_cicsts_packet *p_st_cicsts_packet = *pp_st_cicsts_packet;
    bytebuff_free(&(p_st_cicsts_packet->p_st_packet));
    cicsts_free((void **) pp_st_cicsts_packet);
    return;
}

/*******************************************************************************
*  FUNC     :  释放 L7_cicsts_stmt
*  ARGS     :  **pp_st_cicsts_stmt              (L7_cicsts_stmt)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __cicsts_destroy_stmt(Frhash_header *p_hash_stmt)
{
    frhash2_free2(p_hash_stmt, cicsts_stmt_node_free);
}

int cicsts_session_destory(void *p_st_session_private_in)
{
    CICSTS_PRINT(KBLUE "\ncicsts_session_destory run\n" RESET);
    if (p_st_session_private_in == NULL)
        return FR_SUCC;

    L7session_cicsts_private *p_st_private = (L7session_cicsts_private *) p_st_session_private_in;

    __cicsts_destroy_packet(&(p_st_private->p_st_cicsts_packet));

    __cicsts_destroy_stmt(p_st_private->p_hash_stmt);

    cicsts_free((void **) &p_st_private);

    CICSTS_PRINT_INFO("leave cicsts_session_destory\n");
    return FR_SUCC;
}
